<?php
namespace app\news\model;

use app\admin\facade\Qiniu;
use app\common\upload\Upload;
use think\facade\Env;

class News extends Common
{
    protected $autoWriteTimestamp = true;// 开启自动写入时间戳字段

    /*
     * 定义了修改器之后会在下列情况下触发：
     * 模型对象赋值；
     * 调用模型的data方法，并且第二个参数传入true；
     * 调用模型的save方法，并且传入数据；
     * 显式调用模型的setAttr方法；
     * 定义设置文章的描述，若为空直接截取内容前面的文字
     */
    public function setAbstractAttr($abstract, $news)
    {
        $abstract=str_replace(' ','',$abstract);
        if (empty($abstract)){
            return mb_substr(strip_tags(htmlspecialchars_decode($news['content'])), 0, 100, 'utf-8');
        }else{
            return $abstract;
        }
    }

    public function setContentAttr($content, $data)
    {
        $content=str_replace('src="//','src="http://',$content);
        //获取域名
        $domain=Env::get('qiniu.qiniu_domain');
        $preg='/:\/\/(.*)(\/)/isU';
        preg_match($preg,$domain,$res);
        $domain_preg=str_replace('.','\.',$res[1]);//将域名转换为 image\.4vsy\.com 这个格式拼接到正则中去
        unset($res);
        $preg='/ (src|SRC)=["|\'| ]*(https?:\/\/(?!('.$domain_preg.'))(.*).(gif|jpg|jpeg|bmp|png))/isU';
        $content_markdown=$data['content_markdown'];
        $res=preg_replace_callback($preg,function ($matches)use(&$content_markdown){
            $res= Upload::uploadLink($matches[2]);//待优化,添加上传本地方法
            if($res['code']===0){
                $url=$res['url'];
            }else{
                return ' src="'.$matches[2];
            }
            $need_replace=$matches[2];
            $content_markdown=str_replace($need_replace,$url,$content_markdown);
            return ' src="'.$url;//替换的时候会把 src="去掉 补上去
        },$content);
        $this->set('content_markdown', $content_markdown);//替换markdown图片
        $res= htmlspecialchars($res);
        return $res;
    }
    public function getContentAttr($content)
    {
        return html_entity_decode($content);;
    }

    //
    public function tags()
    {
        return $this->belongsToMany('Tags', '\\app\\admin\\model\\NewsTags', 'tags_id','news_id');
    }
    public function newsCategory()
    {
        return $this->belongsTo('NewsCategory', 'news_category_id', 'id');
    }
    //关联中间表
    public function newsTags()
    {
        return $this->belongsTo(NewsTags::class,'id', 'news_id');
    }
    //关联中间表
    public function comments()
    {
        return $this->hasMany(Comment::class)->order('id','desc');
    }
    //查询右侧最近更新博文
    public function recent_update($total_and_category_id){
        $total=isset($total_and_category_id['total'])?$total_and_category_id['total']:4;
        if(isset($total_and_category_id['category_id'])){
            $this->where(['news_category_id'=>$total_and_category_id['category_id']]);
        }
        $recent_update_news = $this->where('recommend', '1')->order('update_time', 'desc')->limit($total)->select();
        return $recent_update_news;
    }
    //查询点击了排名博文
    public function recent_browse($total_and_category_id){
        $total=isset($total_and_category_id['total'])?$total_and_category_id['total']:8;
        if(isset($total_and_category_id['category_id'])){
            $this->where(['news_category_id'=>$total_and_category_id['category_id']]);
        }
        $recent_browse_news = $this->order(['browse'=>'desc','id'=>'desc'])->limit($total)->select()->toArray();
        $recent_browse_news_top = array_shift($recent_browse_news);
        return array($recent_browse_news_top,$recent_browse_news);
    }
    //查询站长推荐
    public function site_recommend($total_and_category_id){
        $total=isset($total_and_category_id['total'])?$total_and_category_id['total']:8;
        if(isset($total_and_category_id['category_id'])){
            $this->where(['news_category_id'=>$total_and_category_id['category_id']]);
        }
        $recent_site_recommend_news = $this->order(['recommend'=>'desc','hot'=>'desc','top'=>'desc','id'=>'desc'])->limit($total)->select()->toArray();
        $recent_site_recommend_news_top = array_shift($recent_site_recommend_news);
        return array($recent_site_recommend_news_top,$recent_site_recommend_news);
    }
    //查询猜你喜欢
    public function think_you_like($total_and_category_id){
        $total=isset($total_and_category_id['total'])?$total_and_category_id['total']:10;
        if(isset($total_and_category_id['category_id'])){
            $this->where(['news_category_id'=>$total_and_category_id['category_id']]);
        }
        $think_you_like_news = $this->orderRaw('rand()')->limit($total)->select();
        return $think_you_like_news;
    }
}